<?php

namespace app\api\controller;

use addons\exam\library\ExamService;
use addons\exam\model\GradeModel;
use app\admin\model\exam\GradeDetail;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\GradeLog;
use app\common\services\IseService;
use OSS\OssClient;
use push\Push;
use app\common\model\User;
/**
 * 测试接口
 */
class Test extends Api
{
    protected $noNeedLogin = ['createAudio'];
    protected $noNeedRight = ['*'];

    public function index()
    {

        $user_id       = 11;
        $push_clientid = User::where('id',$user_id)->value('push_clientid');
        if(!empty($push_clientid)){
            $param   = [
                'title'         => date('Y-m-d H').' 您的模拟考试专家已点评',
                'push_clientid' => $push_clientid,
                'content'       => date('Y-m-d H').' 您的模拟考试专家已点评',
                'payload'       => [
                    'text'      => date('Y-m-d H').' 您的模拟考试专家已点评',
                    'id'        => 110,
                    'type'      => 1
                ],
            ];
            $param  = json_encode($param);
            $result = Push::send($param);
        }
        
        halt($result);
        halt(json_encode(''));
        $this->success('test');
    }

    function ossupload()
    {
        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        //文件绝对路径
        $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

        try {
            $ret = $oss->uploadFile($config['bucket'], ltrim($attachment->url, "/"), $filePath);
            
            //上传成功后将存储变更为alioss
            $attachment->storage = 'alioss';
            $attachment->save();
            unlink($filePath);
            //成功不做任何操作
        } catch (\Exception $e) {
            $attachment->delete();
            @unlink($filePath);
            $this->error("上传失败");
        }
        return cdnurl($attachment->url, true);
    }
    public function createAudio()
    {
        if(isset(input()['exam'])){
            if(!$this->auth->id){
                return $this->error('请先登录');
            }
        }
        if($_FILES){
            $file_name = $_FILES['file']['name'];// 文件名
            $suffix = substr($file_name,strrpos($file_name,'.'));
            $file_name = time().rand('10000000','99999999');
            if(!isset(input()['text']) || (isset(input()['text']) && !input()['text'])){
                return $this->error('讯飞语音不能为空');
            }


            $fullurl = $this->ossupload();

            $getbinary = file_get_contents($fullurl,false,stream_context_create([
                "ssl" => [
                    "verify_peer"=>false,
                    "verify_peer_name"=>false,
                ]
            ]));
            $upload_dir = __DIR__.'/../../../public/uploads/'.date('Ymd');// 上传文件夹必须存在，否则将移动失败！
            file_put_contents($upload_dir.'/'.$file_name.$suffix,$getbinary);


            if(!file_exists($upload_dir)) {
                @mkdir($upload_dir, 0777);
            }
            $url = $upload_dir.'/'.$file_name.$suffix;
            file_put_contents($url,$getbinary);

            $default = ['sub','ent','category','text','group','check_type','grade','rst','ise_unite','plev'];
            $config = [];
            foreach ($default as $v){
                if(isset(input()[$v]) && input()[$v]){
                    $config[$v] = input()[$v];
                }
            }

            $res = IseService::starting($url,$config);

            @unlink($url);
            if(isset($res['code'])){
                return $this->error(IseService::get_error($res['code']));
            }

            if(isset(input()['exam'])){
                $log_id = input()['log_id'] ?? 0;
                $updatedata = [
                    'red_mark'=>0
                ];
                $cate = $config['category'];
                $insertjson = ['singleRecord'=>$fullurl,'xfyun'=>'','id'=>input('q_id')];
                if(($cate == 'read_sentence' && isset($res[$cate])) || ($cate == 'read_chapter' && isset($res[$cate]))){
                    $eachdata = $res[$cate]['rec_paper']['read_chapter']['sentence']['word'];
                    $chapter = $res[$cate]['rec_paper']['read_chapter'];
                    $insertjson = array_merge($insertjson,["total_score"=>$chapter['total_score'],'accuracy_score'=>$chapter['accuracy_score'],'fluency_score'=>$chapter['fluency_score'],'standard_score'=>$chapter['standard_score']]);
                    foreach ($eachdata as $v){
                        if(isset($v['total_score']) && $v['total_score'] < 3){
                            $updatedata['red_mark'] += 1;
                        }
                    }
                    $grade = GradeLog::where('id',$log_id)->find();
                    if($grade){
                        $num = $grade['sentence_num'] + 1;
                        $gradeupdate['accuracy_score'] = round($grade['accuracy_score'] + $chapter['accuracy_score'] / $num,5);
                        $gradeupdate['fluency_score'] = round($grade['fluency_score'] + $chapter['fluency_score'] / $num,5);
                        $gradeupdate['standard_score'] = round($grade['standard_score'] + $chapter['standard_score'] / $num,5);
                        $gradeupdate['total_score'] = round($grade['total_score'] + $chapter['total_score'] / $num,5);
                        GradeLog::where('id',$log_id)->update($gradeupdate);
                    }
                }
                if($cate == 'word' && isset($res[$cate])){
                    $eachdata = $res[$cate]['rec_paper'][$cate]['sentence']['word'];
                    foreach ($eachdata as $v){
                        if(isset($v['total_score']) && $v['total_score'] < 3){
                            $updatedata['red_mark'] += 1;
                        }
                    }
                }
                $updatedata['content'] = json_encode($insertjson);
                $this->updatedata($updatedata);
            }
            $res['audiourl'] = $fullurl;

            return $this->success('success',$res);
        }
        return $this->error('请上传音频文件');
    }

    private function updatedata($data)
    {
        $qid = input()['q_id'] ?? 0;
        $gradeid = input()['grade_id'] ?? 0;
        $paperid = input()['paper_id'] ?? 0;
        $qst = \app\common\model\Question::where('id',$qid)->find();
        if($qst['kind'] == 'CALL'){
            GradeDetail::create(array_merge([
                'user_id'=>$this->auth->id,
                'question_id'=>input()['q_id'],
                'grade_id'=>input()['grade_id'],
                'paper_id'=>input()['paper_id']
            ],$data));
            return ;
        }

        $gd = GradeDetail::where(['user_id'=>$this->auth->id, 'question_id'=>$qid, 'grade_id'=>$gradeid])->find();
        if($gd){
            $data['red_mark'] = $data['red_mark'] + $gd['red_mark'];
            GradeDetail::where(['user_id'=>$this->auth->id, 'question_id'=>$qid, 'grade_id'=>$gradeid])->update($data);
            GradeModel::where('grade_id',$gradeid)->update(['total_count'=>GradeDetail::where(['user_id'=>$this->auth->id, 'grade_id'=>$gradeid])->count()]);
        }else{
            GradeDetail::create(array_merge([
                'user_id'=>$this->auth->id,
                'question_id'=>input()['q_id'],
                'grade_id'=>input()['grade_id'],
                'paper_id'=>input()['paper_id']
            ],$data));
            GradeModel::where('grade_id',$gradeid)->update(['total_count'=>GradeDetail::where(['user_id'=>$this->auth->id, 'grade_id'=>$gradeid])->count()]);
        }
    }

    public function createGrade()
    {
        $paper_id = input()['paper_id'] ?? 0;
        $log_id = input()['log_id'] ?? 0;
        $num = input()['num'] ?? 0;
        if($num == 1){
            $paper = ExamService::validPaper($paper_id);

            // 记录考试成绩
            $grade = GradeModel::insert(

                [
                    'grade_time'=>0,
                    'error_count'=>0,
                    'right_count'=>0,
                    'total_count'=>0,
                    'total_score'=>0,
                    'is_pass'=>1,
                    'score'=>'0',
                    'cate_id'  => $paper['cate_id'],
                    'user_id'  => $this->auth->id,
                    'paper_id' => $paper_id,
                    'log_id'   => $log_id,
                    'date' => date('Y-m-d'),
                    'mode' =>$paper['mode']
                ],
                false,true);
            return $this->success('success',['grade_id'=>$grade]);
        }
        return $this->success('success');
    }

}
